package com.marver.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.*;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

public class HttpsUtil {
	private static Logger logger = LoggerFactory.getLogger(HttpsUtil.class);
	
    private static class DefaultTrustManager implements X509TrustManager {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    }

    /**
     * 
     * @param uri
     * @return
     * @throws IOException HttpsURLConnection
     */
    public static String getHttpsURLConnection(String uri,String requestMethod,String content) throws IOException {
        SSLContext ctx = null;
        logger.info("Request url="+uri);
        logger.info("Request Data="+content);
        try {
            ctx = SSLContext.getInstance("TLS");
            ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
        } catch (KeyManagementException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        SSLSocketFactory ssf = ctx.getSocketFactory();
        
        URL url = new URL(uri);
        HttpsURLConnection httpsConn = (HttpsURLConnection) url.openConnection();
        httpsConn.setSSLSocketFactory(ssf);
        httpsConn.setHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String arg0, SSLSession arg1) {
                return true;
            }
        });
        //设置输入输出，客户端请求到服务端需要发送数据流(输出流写出),服务端响应给客户端,客户端需要接受数据流(输入流读取)
        httpsConn.setDoOutput(true);
        httpsConn.setDoInput(true);
        httpsConn.setConnectTimeout(10*1000);
        httpsConn.setReadTimeout(30*1000);
        httpsConn.setRequestMethod(requestMethod.toUpperCase());
        // 如果是struts2的action接收请求必须设置此属性,否者接收不到数据流
        httpsConn.setRequestProperty("Content-Type", "application/json");
        httpsConn.setUseCaches(false);
        httpsConn.connect();
        
        //将数据以流的方式写出到服务端
        if(StringUtils.isNotEmpty(content)){
	        DataOutputStream out = new DataOutputStream(httpsConn.getOutputStream());
	        out.write(content.getBytes("UTF-8"));
	        out.flush();
	        out.close();
        }
        //接收服务端响应的数据流
        BufferedReader reader = new BufferedReader(new InputStreamReader(httpsConn.getInputStream(), "UTF-8"));
        StringBuffer buffer = new StringBuffer();
        String line = "";
        while ((line = reader.readLine()) != null) {
                buffer.append(line);
        }
        reader.close();
        logger.info("Response Data="+buffer.toString());
        return buffer.toString();
        
        //return httpsConn;
    }
}
